#!/bin/bash

# Ubuntu 基础配置脚本
set -e

# 创建日志文件
touch jichu.log

# 状态检查函数
check_status() {
    if [ $? -eq 0 ]; then
        echo "✅ $1 成功" | tee -a jichu.log
    else
        echo "❌ $1 失败" | tee -a jichu.log
    fi
}

# 收集用户输入
read -p "请输入要设置的静态 IP 地址: " ip_suffix


# 安装必要工具
apt update
apt install -y  coreutils
check_status "安装 tee"

# 配置时区
timedatectl set-timezone Asia/Shanghai
check_status "设置时区"

# 配置时间同步
apt install -y chrony
check_status "安装 chrony"

cat > /etc/chrony/chrony.conf <<EOF
server ntp.aliyun.com iburst
server time1.aliyun.com iburst
server time2.aliyun.com iburst
server time3.aliyun.com iburst
EOF

systemctl restart chrony
systemctl enable chrony
check_status "配置时间同步"

# 允许 root 登录
sed -i 's/#PermitRootLogin prohibit-password/PermitRootLogin yes/' /etc/ssh/sshd_config
systemctl restart ssh
check_status "启用 root 登录"

# 启用命令行高亮
sed -i 's/#force_color_prompt=yes/force_color_prompt=yes/' /root/.bashrc
check_status "启用命令行高亮"

# 更换软件源
cat > /etc/apt/sources.list <<-EOF
deb https://mirrors.tuna.tsinghua.edu.cn/ubuntu/ noble main restricted universe multiverse 
deb https://mirrors.tuna.tsinghua.edu.cn/ubuntu/ noble-updates main restricted universe multiverse 
deb https://mirrors.tuna.tsinghua.edu.cn/ubuntu/ noble-backports main restricted universe multiverse
EOF

rm -rf /etc/apt/sources.list.d/*
apt update
check_status "更换软件源"

# 安装常用软件
apt install -y vim git bash-completion net-tools wget iputils-ping telnet lrzsz tree zip unzip tcpdump  psmisc file arping bind9-host bind9-dnsutils rsyslog bridge-utils 
check_status "安装常用软件"

# 启用 bash 自动补全
source /etc/profile.d/bash_completion.sh
check_status "启用 bash 自动补全"

# 配置历史命令时间戳
echo 'export HISTTIMEFORMAT="%F %T  "' >> /etc/profile
check_status "配置历史命令时间戳"

# 配置静态 IP
cat > /etc/netplan/50-cloud-init.yaml <<-EOF
network:
  version: 2
  ethernets:
    ens33:
      dhcp4: no
      addresses: [10.0.0.$ip_suffix/24]
      routes:
        - to: default
          via: 10.0.0.2
      nameservers:
        addresses: [10.0.0.2]
EOF

echo "静态 IP 配置完成: 10.0.0.$ip_suffix/24" | tee -a jichu.log

# 应用网络配置
echo "即将应用网络配置，这可能会导致 SSH 连接中断"
read -p "是否继续? (y/n): " confirm

if [ "$confirm" = "y" ] || [ "$confirm" = "Y" ]; then
    netplan apply
    check_status "应用网络配置"
else
    echo "已跳过网络配置应用，请手动执行 'netplan apply'" | tee -a jichu.log
fi

echo "配置完成! 日志保存在: $(pwd)/jichu.log"
